#include "swclientwidget.h"

SWClientWidget::SWClientWidget(QString address, int port)
    : SWCommonWidget()
{
    m_client = NULL;

    connectSignals();
    createClient(address, port);
    setWindowTitle(QString("Client: %1 on port %2")
            .arg(address)
            .arg(port, 0, 10));
}

SWClientWidget::~SWClientWidget()
{
    if (m_client)
        m_client->close();
}

void SWClientWidget::connectSignals()
{
    connect(m_sendLine, SIGNAL(returnPressed()), this, SLOT(sendData()));
    connect(m_outputButton, SIGNAL(clicked()), this, SLOT(sendData()));
}

void SWClientWidget::disconnected()
{
    addEvent("Disconnected", "", "");
    m_client = NULL;
    setConnected(false);
}

void SWClientWidget::createClient(QString address, int port)
{
    m_client = new QTcpSocket;
    m_client->connectToHost(address, port);

    connect(m_client, SIGNAL(connected()), this, SLOT(connected()));
    connect(m_client, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(m_client, SIGNAL(readyRead()), this, SLOT(readyRead()));
    m_client->waitForConnected(-1);
}

void SWClientWidget::connected()
{
    addEvent("Connected", "", "");
    setConnected(true);
    setVisible(true);
}

void SWClientWidget::readyRead()
{
    static char buffer[4096];

    while (1) {
        qint64 lineLen = m_client->readLine(buffer, sizeof(buffer));
        if (lineLen == 0)
            break;

        /* This might contain \0 in it, so use the constructor that specifies a
           size. This is also why no \0 is added to the end. */
        QByteArray data(buffer, lineLen);
        addEvent("Data Received", byteFormat(data), textFormat(data));
    }
}

void SWClientWidget::sendData()
{
    QByteArray data = escapeText(m_sendLine->text());
    if (m_isValidEscape == false) {
        m_statusBar->showMessage(tr("Error: Invalid escape sequence.\n"));
        return;
    }
    else
        m_statusBar->clearMessage();

    if (data.size() == 0)
        return;

    addEvent("Data Sent", byteFormat(data), textFormat(data));
    m_client->write(data);
    m_sendLine->clear();
}
